/**
 * Created by Administrator on 2016/8/30.
 */
"use strict";
swan_pc
    .controller("CompanyExportController",function($scope,$q,companyExport,$timeout,companyExport2,companyExport3,contactExport){
        $scope.QuChong=function(){
            companyExport3.get(function(result){

            })
        };

        //变量定义
        $scope.companyImportList=[];
        //get All Company Information
        $scope.getAllCompany=function(){
            $scope.allCompany=[];
            companyExport.getUserAll(function(result){
                $scope.allCompany=result;
                console.log($scope.allCompany);
            },function(result){
                console.log(result);
            })
        };
        $scope.getAllCompany();
        //Excel 可以直接用 无需读懂原理
        function datenum(v, date1904) {
            if (date1904) {
                v += 1462;
            }
            var epoch = Date.parse(v);
            return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000);
        }
        function sheet_from_array_of_arrays(data) {
            var ws = {};
            var range = {s: {c: 10000000, r: 10000000}, e: {c: 0, r: 0}};
            for (var R = 0; R !== data.length; ++R) {
                for (var C = 0; C !== data[R].length; ++C) {
                    if (range.s.r > R) {
                        range.s.r = R;
                    }
                    if (range.s.c > C) {
                        range.s.c = C;
                    }
                    if (range.e.r < R) {
                        range.e.r = R;
                    }
                    if (range.e.c < C) {
                        range.e.c = C;
                    }
                    var cell = {v: data[R][C]};
                    if (cell.v === null) {
                        continue;
                    }
                    var cell_ref = XLSX.utils.encode_cell({c: C, r: R});

                    if (typeof cell.v === 'number') {
                        cell.t = 'n';
                    } else if (typeof cell.v === 'boolean') {
                        cell.t = 'b';
                    } else if (cell.v instanceof Date) {
                        cell.t = 'n';
                        cell.z = XLSX.SSF._table[14];
                        cell.v = datenum(cell.v);
                    }
                    else {
                        cell.t = 's';
                    }

                    ws[cell_ref] = cell;
                }
            }
            if (range.s.c < 10000000) {
                ws['!ref'] = XLSX.utils.encode_range(range);
            }
            return ws;
        }
        function Workbook() {
            if (!(this instanceof Workbook)) {
                return new Workbook();
            }
            this.SheetNames = [];
            this.Sheets = {};
        }
        //new Company Analyse 导出Export
        var companyExportHeader=[
            {   name:"公司名称",        value:"name", type:"base"},
            {   name:"父公司名称",      value:"parentCompanyId",type:"IdToName"},
            {   name:"公司别名",        value:"alias",type:"base"},
            {   name:"英文名称",        value:"englishName",type:"base"},
            {   name:"类型",            value:"type",type:"base"},
            {   name:"公司概况",        value:"overview",type:"base"},
            {   name:"公司网址",        value:"webSite",type:"base"},
            {   name:"注册日期",        value:"foundDate",type:"base"},
            {   name:"注册资本",        value:"registerCapital",type:"base"},
            {   name:"货币单位",        value:"unit",type:"base"},
            {   name:"公司地址",         value:"addresss",type:"addr"},
            {   name:"和我的业务关系",  value:"businessConnectionWithMe",type:"normal"},
            {   name:"部门",             value:"departments",type:"depar"},
            {   name:"对我的友谊程度",  value:"friendshipWithMe",type:"normal"},
            {   name:"对我的重要性",    value:"importanceToMe",type:"normal"},
            {   name:"全部联系方式",    value:"lineNumbers",type:"line"}
        ];

        var excelBody=[];
        function addressInfoPush(data){
            var address="";
            for(var i=0;i<data.length;i++){
                address = address + "省:"+data[i].province + ",市:" + data[i].city + ",区:" + data[i].district + ",地区:"+data[i].area +",街道:"+ data[i].street +",门牌号:"+ data[i].house
                    +",具体地址:"+data[i].detailAddress+",邮编:"+data[i].postcode+";";
            }
            return address;
        }
        function lineNumber(data){
            var lineNumbers="";
            for(var i=0;i<data.length;i++){
                lineNumbers=lineNumbers+data[i].lineName+":"+data[i].lineNumber+";"
            }
            return lineNumbers;
        }
        var department="";
        function departmentInfoPush(data,preString){
            for (var i = 0; i < data.length; i++) {
                var flag = 0;
                if (preString != "") {
                    department = department + preString + "->" + data[i].name + ";";
                } else {
                    department = department + data[i].name + ";";
                }
                if (data[i].subDepartments.length != 0) {
                    flag = 1;
                    if (preString != "") {
                        preString = preString + "->" + data[i].name;
                    } else {
                        preString = data[i].name;
                    }
                    departmentInfoPush(data[i].subDepartments, preString);
                }
                if (flag == 1) {
                    var pre = preString.split("->");
                    preString = "";
                    for (var j = 0; j < pre.length - 1; j++) {
                        preString = preString + pre[j] + "->";
                    }
                    preString = preString.substring(0, preString.length - 2);
                }
            }
        }
        var departTryData=[];
        function departTry(index,data){
            if(index.length==0){
                for(var i=0;i<data.length;i++){
                    var s={
                        "name":data[i].name,
                        //"duty":data[i].duty,
                        "subDepartments":[]
                    };
                    departTryData.push(s);
                    if(data[i].subDepartments.length!=0){
                        index.push(i);
                        departTry(index,data[i].subDepartments);
                        index.pop();
                    }
                }
            }else if(index.length==1){
                for(var i=0;i<data.length;i++){
                    var s={
                        "name":data[i].name,
                        //"duty":data[i].duty,
                        "subDepartments":[]
                    };
                    departTryData[index[0]].subDepartments.push(s);
                    if(data[i].subDepartments.length!=0){
                        index.push(i);
                        departTry(index,data[i].subDepartments);
                        index.pop();
                    }
                }
            }else if(index.length==2){
                for(var i=0;i<data.length;i++){
                    var s={
                        "name":data[i].name,
                        //"duty":data[i].duty,
                        "subDepartments":[]
                    };
                    departTryData[index[0]].subDepartments[index[1]].subDepartments.push(s);
                    if(data[i].subDepartments.length!=0){
                        index.push(i);
                        departTry(index,data[i].subDepartments);
                        index.pop();
                    }
                }
            }else if(index.length==3){
                for(var i=0;i<data.length;i++){
                    var s={
                        "name":data[i].name,
                        //"duty":data[i].duty,
                        "subDepartments":[]
                    };
                    departTryData[index[0]].subDepartments[index[1]].subDepartments[index[2]].subDepartments.push(s);
                    if(data[i].subDepartments.length!=0){
                        index.push(i);
                        departTry(index,data[i].subDepartments);
                        index.pop();
                    }
                }
            }else if(index.length==4){
                for(var i=0;i<data.length;i++){
                    var s={
                        "name":data[i].name,
                        //"duty":data[i].duty,
                        "subDepartments":[]
                    };
                    departTryData[index[0]].subDepartments[index[1]].subDepartments[index[2]].subDepartments[index[3]].subDepartments.push(s);
                    if(data[i].subDepartments.length!=0){
                        index.push(i);
                        departTry(index,data[i].subDepartments);
                        index.pop();
                    }
                }
            }
        }
        function address1Push(data,key){
            var addr="";
            for(var i=0;i<data.length;i++){
                addr=addr+data[i][key]+";";
            }
            return addr;
        }
        function companyInfoPush(data){
            for(var i=0;i<data.length;i++) {
                var t=[];
                for (var j = 0; j < companyExportHeader.length; j++) {
                    if (companyExportHeader[j].type == "base") {
                        t.push(data[i]["companyBaseInfo"][companyExportHeader[j].value]);
                    } else if (companyExportHeader[j].type == "normal") {
                        t.push(data[i][companyExportHeader[j].value]);
                    } else if (companyExportHeader[j].type == "addr") {
                        t.push(addressInfoPush(data[i][companyExportHeader[j].value]))
                    } else if (companyExportHeader[j].type == "line") {
                        t.push(lineNumber(data[i][companyExportHeader[j].value]));
                    } else if (companyExportHeader[j].type == "IdToName") {
                        t.push(data[i]["parentName"]);
                    } else if (companyExportHeader[j].type == "depar") {
                        var str="";
                        //departmentInfoPush(data[i][companyExportHeader[j].value],str);
                        //t.push(department);
                        //department=""
                        var index=[];
                        departTry(index,data[i][companyExportHeader[j].value]);
                        var department=JSON.stringify(departTryData);
                        t.push(department);

                    }
                }
                excelBody.push(t);
                if(data[i].subCompanys.length!=0){
                    companyInfoPush(data[i].subCompanys);
                }
            }
        }
        $scope.companyExport=function(){
            companyInfoPush($scope.allCompany);
            createExcel(excelBody,"companyInfoExport.xlsx");
        };
        function createExcel(data,file_path){
            var head=getHead();
            var body=[];
            body=data;
            //console.log(head);
            var array = [head,].concat(body);
            var wb = new Workbook(), ws = sheet_from_array_of_arrays(array);

            /* add ranges to worksheet */
            // ws['!merges'] = ranges;
            var ws_name = "Sheet";
            /* add worksheet to workbook */
            wb.SheetNames.push(ws_name);
            wb.Sheets[ws_name] = ws;
            /* bookType can be 'xlsx' or 'xlsm' or 'xlsb' */
            //yinyong
            var wopts = {bookType: 'xlsx', bookSST: true, type: 'binary'};

            var wbout = XLSX.write(wb, wopts);

            function s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
            }
            /* the saveAs call downloads a file on the local machine */
            saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), file_path)
        }
        function getHead(){
            var h=[];
            _.forEach(companyExportHeader,function(data,index,array){
                h.push(data.name);
            });
            return h;
        }
        //导入
        $scope.errorMessage=[];
        var importHeader=[
            {   name:"公司名称",        value:"name", type:"baseString"},
            {   name:"父公司名称",      value:"parentCompanyId",type:"parentName"},
            /*{   name:"公司别名",        value:"alias",type:"baseString"},
            {   name:"英文名称",        value:"englishName",type:"baseString"},
            {   name:"类型",            value:"type",type:"baseString"},
            {   name:"公司概况",        value:"overview",type:"baseString"},
            {   name:"公司网址",        value:"webSite",type:"baseString"},
            {   name:"注册日期",        value:"foundDate",type:"baseDate"},
            {   name:"注册资本",        value:"registerCapital",type:"baseInt"},
            {   name:"货币单位",        value:"unit",type:"baseUnit"},

            {   name:"省",               value:"province",type:"addr"},
            {   name:"市",               value:"city",type:"addr"},
            {   name:"区",               value:"district",type:"addr"},
            {   name:"街道",             value:"area",type:"addr"},
            {   name:"详细地址",         value:"detail_address",type:"addr"},
            {   name:"邮编",             value:"postcode",type:"addr"},
            {   name:"电话号码",         value:"lineNumbers",type:"line"},
            {   name:"和我的业务关系",  value:"businessConnectionWithMe",type:"connection"},
            {   name:"对我的友谊程度",  value:"friendshipWithMe",type:"friend"},
            {   name:"对我的重要性",    value:"importanceToMe",type:"importance"},*/

        ];
        //去左右空格;
        function trim(s){
            return s.replace(/(^\s*)|(\s*$)/g, "");
        }
        function headerCheck(data){
            var i=0;
            for( var s in data){
                //console.log(data[s]+"      "+importHeader[i].name);
                if(data[s]!=importHeader[i++].name){
                    var errString="首行字段: '"+data[s]+ "' 与系统要求字段 '"+importHeader[i].name+"' 不符";
                    $scope.errorMessage.push(errString);
                }
            }
        }
        function bodyCheck(data){
            for(var i=1;i<data.length;i++){  //分行检测每个公司
                /*if(data[i][0]=="" || data[i][0]==undefined){
                    var errString="第"+(i+1)+"行第1列公司名称不能为空";
                    $scope.errorMessage.push(errString);
                }else{*/
                    /*var pattern=/^(\d{4})(-|\/)(\d{1,2})(-|\/)(\d{1,2})$/;
                    var res=pattern.test(data[i][7]);*/
                    //注册资本正字表达式匹配
                    //var currency=["RMB","USD","EURO","NIPPON","LUBU","HKD","TWD","THAI"];
                    var currency=["人民币","美元","欧元","日元","卢布","港币","新台币","泰铢"];
                    //var businessConnection=["CUSTOMER","PARTNER","COMPETITOR","PROSPECT","PEERS","VENDOR","ADMINISTRATION","OTHER"];
                    var businessConnection=["客户","合作伙伴","竞争对手","供应商","其他"];
                    //var friendShip=["HATE","TROUBLE","DISLIKE","ANNOYING","NO","KNOW","OK","FINE","NICE","LIKE"];
                    var friendShip=["讨厌","烦","认识","接受","好感"];
                    //var importance=["NEED","IMPORTANT","VITAL","CRITICAL","NO"];
                    var importance=["不需要","需要","重要","很重要","极其重要"];
                    //货币单位被选值检查
                    if(data[i][9]!="" && data[i][9]!=undefined) {
                        var flag = 0;
                        for (var j = 0; j < currency.length; j++) {
                            if (data[i][9].toUpperCase() == currency[j]) {
                                flag = 1;
                            }
                        }
                        if (flag == 0) {
                            var errString = "第" + (i + 1) + "行第10列  '货币单位' 应使用被选值 [人民币,美元,欧元,日元,卢布,港币,新台币,泰铢]";
                            $scope.errorMessage.push(errString);
                        }
                    }
                    //和我的业务关系 被选值检查
                    if(data[i][17]!="" && data[i][17]!=undefined) {
                        flag = 0;
                        for (var j = 0; j < businessConnection.length; j++) {
                            if (data[i][17] == businessConnection[j]) {
                                flag = 1;
                            }
                        }
                        if (flag == 0) {
                            var errString = "第" + (i + 1) + "行第12列  '和我的业务关系' 应使用被选值 [客户,合作伙伴,竞争对手,供应商,其他]";
                            $scope.errorMessage.push(errString);
                        }
                    }
                    //对我的友谊程度 被选值检查
                    if(data[i][18]!="" && data[i][18]!=undefined) {
                        flag = 0;
                        for (var j = 0; j < friendShip.length; j++) {
                            if (data[i][18] == friendShip[j]) {
                                flag = 1;
                            }
                        }
                        if (flag == 0) {
                            var errString = "第" + (i + 1) + "行第14列  '对我的友谊程度' 应使用被选值 [不需要,需要,重要,很重要,极其重要]";
                            $scope.errorMessage.push(errString);
                        }
                    }
                    //对我的重要性 被选值检查
                    if(data[i][19]!="" && data[i][19]!=undefined) {
                        flag = 0;
                        for (var j = 0; j < importance.length; j++) {
                            if (data[i][19] == importance[j]) {
                                flag = 1;
                            }
                        }
                        if (flag == 0) {
                            var errString = "第" + (i + 1) + "行第15列  '对我的重要性' 应使用被选值 [不需要,需要,重要,很重要,极其重要]";
                            $scope.errorMessage.push(errString);
                        }
                    }
                //}
            }
            for(var i=0;i<$scope.errorMessage.length;i++){
                console.log(i+1+": "+$scope.errorMessage[i]);
                console.log("\n");
            }
        }
        function analyseCompany(data){
            //console.log(data);
            var s={
                id:null,
                name:null
            };
            for(var i=0;i<data.length;i++){
                s.id=data[i].id;
                s.name=data[i].companyBaseInfo.name;
                $scope.companyIdNameList.push(s);
                if(data[i].subCompanys.length!=0){
                    analyseCompany(data[i].subCompanys);
                }
            }
            //console.log($scope.companyIdNameList);
        }
        function getCurrentCompany(){
            var def1=$q.defer();
            var pro1=def1.promise;
            $scope.companyIdNameList=[];
            companyExport.getUserAll(function(result){
                $scope.allCompany=result;
                def1.resolve();
            },function(result){
            });
            pro1.then(function(){
                analyseCompany($scope.allCompany);
            })
        }
        function parentNameToId(data){
            for(var i=0;i<$scope.companyIdNameList.length;i++){
                if(data==$scope.companyIdNameList[i].name){
                    var id=$scope.companyIdNameList[i].id;
                    return id;
                }
            }
        }
        function companyNameCheck(data){
            //console.log($scope.companyIdNameList.length);
            for(var i=0;i<$scope.companyIdNameList.length;i++){
                //console.log(data+"    "+$scope.companyIdNameList[i].name);
                if(data==$scope.companyIdNameList[i].name){
                    return false;
                }
            }
            return true;
        }
        function addressInfoSave(data){
            if(data!=""&&data!=undefined) {
                var addrList = data.split(";");
                for (var i = 0; i < addrList.length - 1; i++) {
                    var add = {
                        "area": "",
                        "city": "",
                        "detailAddress": "",
                        "district": "",
                        "house": "",
                        "postcode": "",
                        "province": "",
                        "street": ""
                    };
                    var address = addrList[i].split(",");
                    for (var j = 0; j < address.length; j++) {
                        var addressDetail = address[j].split(":");
                        if (addressDetail[0] == "省") {
                            add.province = addressDetail[1];
                        } else if (addressDetail[0] == "市") {
                            add.city = addressDetail[1];
                        } else if (addressDetail[0] == "区") {
                            add.district = addressDetail[1];
                        } else if (addressDetail[0] == "地区") {
                            add.area = addressDetail[1];
                        } else if (addressDetail[0] == "街道") {
                            add.street = addressDetail[1];
                        } else if (addressDetail[0] == "门牌号") {
                            add.house = addressDetail[1];
                        } else if (addressDetail[0] == "具体地址") {
                            add.detailAddress = addressDetail[1];
                        } else if (addressDetail[0] == "邮编") {
                            add.postcode = addressDetail[1];
                        }
                    }
                    $scope.addCompanyInfo.addresss.push(add);
                }
            }
        }
        function lineNumberSave(data){
            if(data!="" && data!=undefined) {
                /*var num = data.split(";");
                for (var i = 0; i < num.length - 1; i++) {
                    var s = {
                        "lineName": "",
                        "lineNumber": ""
                    };
                    var number = num[i].split(":");
                    if (number[0] != "" || number[1] != "") {
                        s.lineName = number[0];
                        s.lineNumber = number[1];
                        $scope.addCompanyInfo.lineNumbers.push(s);
                    }
                }*/
                console.log(data);
                var numbers=data.split(",");
                var numberFlag=0;
                for(var i=0;i<numbers.length-1;i++){
                    numberFlag++;
                    var s={
                        "lineName":numberFlag.toString(),
                        "lineNumber":numbers[i]
                    };
                    $scope.addCompanyInfo.lineNumbers.push(s);
                }
            }
        }

        var resultCompany=[];
        function companySave(data){
            //data[0]=trim(data[0]);
            //$scope.addCompanyInfo.companyBaseInfo.name=data[0];
            /*if(data[1]!=""&&data[1]!=undefined) {
                data[1]=trim(data[1]);
                $scope.addCompanyInfo.parentCompanyId = parentNameToId(data[1]);
            }*/
            /*$scope.addCompanyInfo.companyBaseInfo.alias=data[2];
            $scope.addCompanyInfo.companyBaseInfo.englishName=data[3];
            $scope.addCompanyInfo.companyBaseInfo.type=data[4];
            $scope.addCompanyInfo.companyBaseInfo.overview=data[5];
            $scope.addCompanyInfo.companyBaseInfo.webSite=data[6];
            $scope.addCompanyInfo.companyBaseInfo.foundDate=new Date(data[7]);
            $scope.addCompanyInfo.companyBaseInfo.registerCapital=data[8];
            switch(data[9]){
                case "人民币":
                    $scope.addCompanyInfo.companyBaseInfo.unit="0";
                    break;
                case "美元":
                    $scope.addCompanyInfo.companyBaseInfo.unit="1";
                    break;
                case "欧元":
                    $scope.addCompanyInfo.companyBaseInfo.unit="2";
                    break;
                case "日元":
                    $scope.addCompanyInfo.companyBaseInfo.unit="3";
                    break;
                case "卢布":
                    $scope.addCompanyInfo.companyBaseInfo.unit="4";
                    break;
                case "港币":
                    $scope.addCompanyInfo.companyBaseInfo.unit="5";
                    break;
                case "新台币":
                    $scope.addCompanyInfo.companyBaseInfo.unit="6";
                    break;
                case "泰铢":
                    $scope.addCompanyInfo.companyBaseInfo.unit="7";
                    break;
            }
            var address = {
                "area": "",
                "city": "",
                "detailAddress": "",
                "district": "",
                "house": "",
                "postcode": "",
                "province": "",
                "street": ""
            };
            address.province=data[10];
            address.city=data[11];
            address.district=data[12];
            address.street=data[13];
            address.detailAddress=data[14];
            address.postcode=data[15];
            $scope.addCompanyInfo.addresss.push(address);
            //lineNumberSave(data[16]);
            switch(data[17]){
                case "客户":
                    $scope.addCompanyInfo.businessConnectionWithMe="0";
                    break;
                case "合作伙伴":
                    $scope.addCompanyInfo.businessConnectionWithMe="1";
                    break;
                case "竞争对手":
                    $scope.addCompanyInfo.businessConnectionWithMe="2";
                    break;
                case "供应商":
                    $scope.addCompanyInfo.businessConnectionWithMe="3";
                    break;
                case "其他":
                    $scope.addCompanyInfo.businessConnectionWithMe="4";
                    break;
            }
            switch(data[18]){
                case "讨厌":
                    $scope.addCompanyInfo.friendshipWithMe="0";
                    break;
                case "烦":
                    $scope.addCompanyInfo.friendshipWithMe="1";
                    break;
                case "认识":
                    $scope.addCompanyInfo.friendshipWithMe="2";
                    break;
                case "接受":
                    $scope.addCompanyInfo.friendshipWithMe="3";
                    break;
                case "好感":
                    $scope.addCompanyInfo.friendshipWithMe="4";
                    break;
            }
            switch(data[19]){
                case "不需要":
                    $scope.addCompanyInfo.importanceToMe="0";
                    break;
                case "需要":
                    $scope.addCompanyInfo.importanceToMe="1";
                    break;
                case "重要":
                    $scope.addCompanyInfo.importanceToMe="2";
                    break;
                case "很重要":
                    $scope.addCompanyInfo.importanceToMe="3";
                    break;
                case "极其重要":
                    $scope.addCompanyInfo.importanceToMe="4";
                    break;
            }*/
            $scope.addCompanyInfo.name=data[0];
            $scope.addCompanyInfo.parentName=data[1];
            //console.log($scope.companyIdNameList);
            //var nameCheck=companyNameCheck(data[0]);
            //console.log(nameCheck);
            if($scope.addCompanyInfo.companyBaseInfo.name!="" && $scope.addCompanyInfo.companyBaseInfo.name!= undefined){
                console.log();
                companyExport.save($scope.addCompanyInfo,function(result){
                    console.log("success");
                    console.log(result);
                },function(result){
                    console.log("error");
                    console.log(result);
                })
            }
            /*if(companyNameCheck(data[0]) && $scope.addCompanyInfo.parentCompanyId!=undefined){
                if($scope.addCompanyInfo.companyBaseInfo.name!="" && $scope.addCompanyInfo.companyBaseInfo.name!= undefined){
                    companyExport.save($scope.addCompanyInfo,function(result){
                        console.log("success");
                        console.log(result);
                    },function(result){
                        console.log("error");
                        console.log(result);
                    })
                }
            }else if(!companyNameCheck(data[0])){
                var errString="公司名 '"+data[0]+" '与已有公司名冲突，已自动忽略导入该公司信息";
                $scope.errorMessage.push(errString);
            }else if($scope.addCompanyInfo.parentCompanyId!=undefined){
                var errString="公司 '"+data[0]+ " '的父公司' "+data[1]+" '未找到，系统已自动忽略该公司信息"
            }*/
            //console.log($scope.addCompanyInfo);
        }
        function companyImport(){
            var data=$scope.companyImportList;
            //getCurrentCompany();
            var def2=$q.defer();
            var pro2=def2.promise;
            $scope.companyIdNameList=[];
            companyExport.getUserAll(function(result){
                $scope.allCompany=result;
                def2.resolve();
            },function(result){
            });
            pro2.then(function(){
                analyseCompany($scope.allCompany);
                $scope.addCompanyInfo={
                    "addresss": [],
                    "businessConnectionWithMe": "",
                    "companyBaseInfo": {
                        "alias": "",
                        "businessConnection": "",
                        "englishName": "",
                        "foundDate": "",
                        "friendship": "",
                        "importance": "",
                        "isRelated": false,
                        "isTop": true,
                        "name": "",
                        "overview": "",
                        "registerCapital": 0,
                        "type": "",
                        "unit": "",
                        "webSite": ""
                    },
                    "departments": [],
                    "parentCompanyId":"",
                    "friendshipWithMe": "",
                    "importanceToMe": "",
                    "lineNumbers": [],
                    "subCompanys": [
                    ]
                };
                var saveFlag=0;
                for(var i=1;i<data.length;i++){
                    if(data[i][0]!="" && data[i][0]!=undefined){
                        //先存没有父公司的
                        console.log(data[i]);
                        console.log(data[i][1]);
                        if(data[i][1]==""||data[i][1]==undefined){
                            saveFlag=1;
                            companySave(data[i]);
                            console.log($scope.companyImportList);
                            $scope.companyImportList.splice(i,1);
                            console.log($scope.companyImportList);
                        }else {
                            //再存能找到父公司的
                            var parentFlag = 0;
                            for (var j = 0; j < $scope.companyIdNameList.length; j++) {
                                data[i][1]=trim(data[i][1]);
                                if (data[i][1] == $scope.companyIdNameList[j].name) {
                                    parentFlag = 1;
                                }
                            }
                            if (parentFlag == 1) {
                                saveFlag = 1;
                                companySave(data[i]);
                                $scope.companyImportList.splice(i, 1);
                            } else {
                                //var errString = "公司 '" + data[i][0] + " '找不到对应的父公司，系统已自动忽略该公司信息";
                                /*var errString="公司 '"+data[i][0]+ "' 的父公司 '"+data[i][1]+"' 未找到，系统已自动忽略该公司信息"
                                errorMessage.push(errString);*/
                            }
                        }
                        //console.log(i);
                        //console.log($scope.companyImportList);
                    }
                }
                $timeout(function(){
                    console.log("saveFlag:"+saveFlag);
                    if(saveFlag==1){
                        companyImport();
                    }else{
                        console.log($scope.errorMessage);
                    }
                },2000);
            });
        }

        function companyImport2(){
            var data=$scope.companyImportList;
            $scope.resultCompany=[];
            $scope.addCompanyInfo={
                "list":null
            };
            for(var i=1;i<data.length;i++){
                if(data[i][0]!="" && data[i][0]!=undefined){
                    var info={
                        "name":data[i][0],
                        "parentName":data[i][1]
                    };
                    $scope.resultCompany.push(info);
                }
            }
            $scope.addCompanyInfo.list=$scope.resultCompany;
            console.log($scope.addCompanyInfo);
            companyExport2.save($scope.addCompanyInfo,function(result){
                console.log(result);
            },function(result){
                console.log(result);
            })
        }


        $scope.handleContact=function(data) {
            $scope.addContact = {
                list: null
            };
            $scope.contact={
                "name":null,
                "userCompanyName":null,
                "birthDate":null,
                "englishName":null,
                "gender":null,
                "businessConnection":null,
                "friendshipToMe":null,
                "level":null,
                "department":null,
                "position":null,
                "professionsType":null,
                "responsibility":null,
                "hobby":null,
                "mobileNumber":null,
                "email":null,
                "fixedNumber":null,
                "province":null,
                "city":null,
                "district":null,
                "street":null,
                "detailAddress":null,
                "postcode":null,
                "remark":null
            };
            if ((data[0] == "" || data[0] == undefined ) && (data[3] == "" || data[3] == undefined)) {

            } else {
                if (data[0] != "" && data[0] != undefined) {
                    $scope.contact.name = data[0];
                } else {
                    $scope.contact.name = data[3];
                }
                $scope.contact.userCompanyName = data[1];
                $scope.contact.birthDate = new Date(data[2]);
                $scope.contact.englishName = data[3];
                if (data[4] == "M") {
                    $scope.contact.gender = 1;
                } else if (data[4] == "F") {
                    $scope.contact.gender = 0;
                }
                switch (data[5]) {
                    case "客户":
                        $scope.contact.businessConnection = "0";
                        break;
                    case "合作伙伴":
                        $scope.contact.businessConnection = "1";
                        break;
                    case "竞争对手":
                        $scope.contact.businessConnection = "2";
                        break;
                    case "争取对象":
                        $scope.contact.businessConnection = "3";
                        break;
                    case "同行":
                        $scope.contact.businessConnection = "4";
                        break;
                    case "供应商":
                        $scope.contact.businessConnection = "5";
                        break;
                    case "行政管理":
                        $scope.contact.businessConnection = "6";
                        break;
                    case "其他":
                        $scope.contact.businessConnection = "7";
                        break;
                }
                switch (data[6]) {
                    case "hate":
                        $scope.contact.friendshipToMe = "0";
                        break;
                    case "烦":
                        $scope.contact.friendshipToMe = "1";
                        break;
                    case "know":
                        $scope.contact.friendshipToMe = "2";
                        break;
                    case "只是认识":
                        $scope.contact.friendshipToMe = "2";
                        break;
                    case "互相接受":
                        $scope.contact.friendshipToMe = "3";
                        break;
                    case "互相喜欢":
                        $scope.contact.friendshipToMe = "4";
                        break;
                }
                switch (data[7]) {
                    case "入门级":
                        $scope.contact.level = "0";
                        break;
                    case "初级":
                        $scope.contact.level = "1";
                        break;
                    case "中级":
                        $scope.contact.level = "2";
                        break;
                    case "高级":
                        $scope.contact.level = "3";
                        break;
                    case "最高级":
                        $scope.contact.level = "4";
                        break;
                }
                $scope.contact.department = data[8];
                $scope.contact.position = data[9];
                switch (data[10]) {
                    case "销售":
                        $scope.contact.professionsType = "0";
                        break;
                    case "管理":
                        $scope.contact.professionsType = "1";
                        break;
                    case "技术":
                        $scope.contact.professionsType = "2";
                        break;
                    case "市场":
                        $scope.contact.professionsType = "3";
                        break;
                    case "财务":
                        $scope.contact.professionsType = "4";
                        break;
                    case "运营":
                        $scope.contact.professionsType = "5";
                        break;
                    case "人力资源":
                        $scope.contact.professionsType = "6";
                        break;
                    case "信息化":
                        $scope.contact.professionsType = "7";
                        break;
                    case "生产":
                        $scope.contact.professionsType = "8";
                        break;
                    case "通讯":
                        $scope.contact.professionsType = "9";
                        break;
                    case "交通":
                        $scope.contact.professionsType = "10";
                        break;
                    case "教育":
                        $scope.contact.professionsType = "11";
                        break;
                    case "法律":
                        $scope.contact.professionsType = "12";
                        break;
                    case "医疗":
                        $scope.contact.professionsType = "13";
                        break;
                    case "新闻出版":
                        $scope.contact.professionsType = "14";
                        break;
                    case "文化艺术":
                        $scope.contact.professionsType = "15";
                        break;
                    case "金融":
                        $scope.contact.professionsType = "16";
                        break;
                    case "保险":
                        $scope.contact.professionsType = "17";
                        break;
                    case "宗教":
                        $scope.contact.professionsType = "18";
                        break;
                    case "军人":
                        $scope.contact.professionsType = "19";
                        break;
                    case "体育":
                        $scope.contact.professionsType = "20";
                        break;
                }
                $scope.contact.responsibility = data[11];
                $scope.contact.hobby = data[12];
                switch (data[13]) {
                    case "不需要":
                        $scope.contact.importanceToMe = "0";
                        break;
                    case "不重要":
                        $scope.contact.importanceToMe = "0";
                        break;
                    case "需要":
                        $scope.contact.importanceToMe = "1";
                        break;
                    case "重要":
                        $scope.contact.importanceToMe = "2";
                        break;
                    case "很重要":
                        $scope.contact.importanceToMe = "3";
                        break;
                    case "极其重要":
                        $scope.contact.importanceToMe = "4";
                        break;
                }
                $scope.contact.mobileNumber = data[14];
                $scope.contact.email = data[15];
                $scope.contact.fixedNumber = data[16];
                $scope.contact.province = data[17];
                $scope.contact.city = data[18];
                $scope.contact.district = data[19];
                $scope.contact.street = data[20];
                $scope.contact.detailAddree = data[21];
                $scope.contact.postcode = data[22];
                if(data[23]!=null && data[23]!=undefined){
                    if(data[23].length>110){
                        data[23]=data[23].substring(0,110);
                    }
                }
                $scope.contact.remark = data[23];
                console.log($scope.contact);
                var contact = $scope.contact;
                $scope.resultContact.push(contact);
            }
        }

        function contactImport(){
            var data = $scope.companyImportList;
            $scope.resultContact=[];
            for(var i=1;i<data.length;i++){
                /*if((data[i][0]==""|| data[i][0]==undefined )&& (data[i][3]=="" || data[i][3]==undefined)){

                }else{
                    if(data[i][0]!=""&&data[i][0]!=undefined){
                        $scope.contact.name=data[i][0];
                    }else{
                        $scope.contact.name=data[i][3];
                    }
                    $scope.contact.userCompanyName=data[i][1];
                    $scope.contact.birthDate=new Date(data[i][2]);
                    $scope.contact.englishName=data[i][3];
                    if(data[i][4]=="M"){
                        $scope.contact.gender="0";
                    }else if(data[i][4]=="F"){
                        $scope.contact.gender="1";
                    }
                    switch(data[i][5]){
                        case "客户":
                            $scope.contact.businessConnection="0";
                        case "合作伙伴":
                            $scope.contact.businessConnection="1";
                        case "竞争对手":
                            $scope.contact.businessConnection="2";
                        case "争取对象":
                            $scope.contact.businessConnection="3";
                        case "同行":
                            $scope.contact.businessConnection="4";
                        case "供应商":
                            $scope.contact.businessConnection="5";
                        case "行政管理":
                            $scope.contact.businessConnection="6";
                        case "其他":
                            $scope.contact.businessConnection="7";
                    }
                    switch(data[i][6]){
                        case "hate":
                            $scope.contact.friendshipToMe="0";
                        case "烦":
                            $scope.contact.friendshipToMe="1";
                        case "know":
                            $scope.contact.friendshipToMe="2";
                        case "只是认识":
                            $scope.contact.friendshipToMe="2";
                        case "互相接受":
                            $scope.contact.friendshipToMe="3";
                        case "互相喜欢":
                            $scope.contact.friendshipToMe="4";
                    }
                    switch(data[i][7]){
                        case "入门级":
                            $scope.contact.level="0";
                        case "初级":
                            $scope.contact.level="1";
                        case "中级":
                            $scope.contact.level="2";
                        case "高级":
                            $scope.contact.level="3";
                        case "最高级":
                            $scope.contact.level="4";
                    }
                    $scope.contact.department=data[i][8];
                    $scope.contact.position=data[i][9];
                    switch(data[i][10]){
                        case "销售":
                            $scope.contact.professionsType="0";
                        case "管理":
                            $scope.contact.professionsType="1";
                        case "技术":
                            $scope.contact.professionsType="2";
                        case "市场":
                            $scope.contact.professionsType="3";
                        case "财务":
                            $scope.contact.professionsType="4";
                        case "运营":
                            $scope.contact.professionsType="5";
                        case "人力资源":
                            $scope.contact.professionsType="6";
                        case "信息化":
                            $scope.contact.professionsType="7";
                        case "生产":
                            $scope.contact.professionsType="8";
                        case "通讯":
                            $scope.contact.professionsType="9";
                        case "交通":
                            $scope.contact.professionsType="10";
                        case "教育":
                            $scope.contact.professionsType="11";
                        case "法律":
                            $scope.contact.professionsType="12";
                        case "医疗":
                            $scope.contact.professionsType="13";
                        case "新闻出版":
                            $scope.contact.professionsType="14";
                        case "文化艺术":
                            $scope.contact.professionsType="15";
                        case "金融":
                            $scope.contact.professionsType="16";
                        case "保险":
                            $scope.contact.professionsType="17";
                        case "宗教":
                            $scope.contact.professionsType="18";
                        case "军人":
                            $scope.contact.professionsType="19";
                        case "体育":
                            $scope.contact.professionsType="20";
                    }
                    $scope.contact.responsibility=data[i][11];
                    $scope.contact.hobby=data[i][12];
                    switch(data[i][13]){
                        case "不需要":
                            $scope.contact.importanceToMe="0";
                        case "不重要":
                            $scope.contact.professionsType="0";
                        case "需要":
                            $scope.contact.professionsType="0";
                        case "重要":
                            $scope.contact.professionsType="0";
                        case "很重要":
                            $scope.contact.professionsType="0";
                        case "极其重要":
                            $scope.contact.professionsType="0";
                    }
                    $scope.contact.mobileNumber=data[i][14];
                    $scope.contact.email=data[i][15];
                    $scope.contact.fixedNumber=data[i][16];
                    $scope.contact.province=data[i][17];
                    $scope.contact.city=data[i][18];
                    $scope.contact.district=data[i][19];
                    $scope.contact.street=data[i][20];
                    $scope.contact.detailAddree=data[i][21];
                    $scope.contact.postcode=data[i][22];
                    $scope.contact.remark=data[i][23];
                    console.log($scope.contact);
                    console.log(data[i]);
                    var contact=$scope.contact;
                    $scope.resultContact.push(contact);*/
                $scope.handleContact(data[i]);
            }
            $scope.addContact.list=$scope.resultContact;
            console.log($scope.addContact)
            contactExport.save($scope.addContact,function(result){
            });
        }

        function sheet_to_data(data){
            var first_sheet_name=data.SheetNames[0];
            var worksheet=data.Sheets[first_sheet_name];
            var json = XLSX.utils.sheet_to_json(worksheet, {header: 1, raw: true});
            $scope.companyImportList=json;
            $scope.errorMessage=[];
            //headerCheck(json[0]);
            //bodyCheck(json);
            // if($scope.errorMessage.length==0) {
            //     companyImport2();
            // }
            contactImport();
        }
        $scope.upExcel = function (file) {
            if(!file)return;
            var reader = new FileReader();
            var name = file.name;
            reader.onload = function (e) {
                var data = e.target.result;
                var workbook = XLSX.read(data, {type: 'binary'});
                sheet_to_data(workbook);
                //var array=sheet_to_data(workbook);
                /* DO SOMETHING WITH workbook HERE */
            };
            reader.readAsBinaryString(file);
        };
        //错误信息更新
        $scope.messageView=[];
        $scope.errorMessage=[];
        //$scope.messageView=[{value:"sb"},{value:"sb2"},{value:"sb3"}];
        $scope.$watch(function(){
            return $scope.errorMessage;
        },function(){
            $scope.messageView=$scope.errorMessage;
        })
    });
